<?php

namespace App\Api\Eloquent;

use App\Admin\Eloquent\Code;
use App\Eloquent\Information;
use App\Admin\Eloquent\ProfitRole;
use App\Admin\Eloquent\OrganizationalUser;
use DB;

class Projects extends Model
{
    /*
     * 获取项目列表
     */
    public static function get_projects($cate = null, $num = null, $page = 0)
    {
        //新手标
        if ($cate == 'beginners') {
            $status = array('rush');
            $projects = Projects::where('new_projects', 1)
                ->whereIn('status', $status)
                ->where('start_time','<',date('Y-m-d H:i:s'))
                ->orderBy('sort', 'asc')
                ->orderBy('published_at', 'desc')
                ->limit(1)
                ->get();
            return $projects;

        }
        //精选项目
        if ($cate == 'projects') {
            $a = $page * 5;
            $status = array('rush');
            $projects = Projects::where('new_projects', 0)
                ->whereIn('status', $status)
                ->where('start_time','<',date('Y-m-d H:i:s'))
                ->orderBy('sort', 'asc')
                ->orderBy('published_at', 'desc')
                ->skip($a)
                ->limit(5)
                ->get();
            return $projects;
        }
        //获取所有项目，按排序排正序
        if ($cate == null) {
            $a = $page * 5;
            $status = array('rush', 'full', 'payment', 'finish');
            $projects = Projects::join('codes','codes.code','=','status')
                ->select( DB::raw('projects.financed_money/projects.finance_money as toauto'),'projects.*','codes.code','codes.sort' )
                ->where('project_type_template_id', '=', $num)
                ->where('start_time','<',date('Y-m-d H:i:s'))
                ->whereIn('status', $status)
                ->orderBy('codes.sort','desc')
                ->orderBy('projects.sort', 'desc')
                ->orderBy('new_projects', 'desc')
                ->orderBy('published_at', 'desc')
                ->skip($a)
                ->limit(5)
                ->get();
            if ($projects->count()){
                $r_projects = Projects::getalltail($projects);
                return $r_projects;
            }
            return $projects;
        }
    }

    /*
     * 获取单个项目
     */
    public static function getOneProjects($id)
    {
        $status = array('rush','full','finish','payment');
        $data = Projects::join('codes', 'codes.code', '=', 'repayment')
            ->where('id', '=', $id)
            ->whereIn('status', $status)
            ->select('codes.name as repayment_name', 'projects.*')
            ->get();
        return $data;
    }

    /*
     * 获取单个项目投资详情
     */
    public function getOneTail()
    {
        $data = ProjectsUser::where('projects_id', '=', $this->id)
            ->get();
        return $data;
    }

    /*
     * 获取项目的投资人数和已投金额
     * $projects为一组对像
     */
    public static function getalltail($projects)
    {
        foreach ($projects as $project) {
            $project->repayment_name=Code::where('code',$project->repayment)->value('name');
            $project->collateral_name=Code::where('code',$project->collateral_type)->value('name');
            $projects_id[] = $project->id;
            $project->detail = null;
            $project->had_money = 0.00;
            $project->ratio = 0.00;
            $project->user_num = '0';
            if ($project->finance_time_cate == 'd') {
                $project->r_finance_time_cate = '天';
            } elseif ($project->finance_time_cate == 'm') {
                $project->r_finance_time_cate = '个月';
            } elseif($project->finance_time_cate == 'y') {
                $project->r_finance_time_cate = '年';
            } elseif($project->finance_time_cate == 'mm'){
                $project->r_finance_time_cate = '个月';
            }

            //获取该项目的信息模板
            //担保模板
//            $project->collateral_tmp='3';
//            $project->collateral_name = OrganizationalUser::Where('user_id','=',$project->collateral_id)->value('company_name');

            $r_projects[$project->id] = $project;
            $r_details[$project->id] = array();
        }
        //获取该组项目的所有投资详细

        $details = ProjectsUser::whereIn('projects_id', $projects_id)
            ->get();
        //把投资详细分组
        foreach ($details as $detail) {
            $r_details[$detail->projects_id][$detail->id] = $detail;
        }
        foreach ($r_details as $key => $r_detail) {
            $money = array();
            foreach ($r_detail as $one_detail) {
                $money[] = $one_detail->invest_money;
            }
            $user_num = collect($money)->count();

            $add_money = $r_projects[$key]->financed_money;
            $finance_money = $r_projects[$key]->finance_money;
            if($finance_money>=10000){
                $r_projects[$key]->money=$finance_money/10000;
                $r_projects[$key]->money_cate='万';
            }
            else{
                $r_projects[$key]->money=number_format($finance_money,2);
                $r_projects[$key]->money_cate='元';
            }
            //项目融资详情
            $r_projects[$key]->detail = $r_detail;
            //项目融资比例
            $r_projects[$key]->ratio = ($add_money*100/ $finance_money);
            $r_projects[$key]->r_ratio = number_format($r_projects[$key]->ratio,2);//格式0.00;
            //项目还需投资金额
            $r_projects[$key]->need_money=number_format($finance_money-$add_money,2);
            $r_projects[$key]->r_need_money=$finance_money-$add_money;
            //项目起投金额
            $r_projects[$key]->finance_rule_money_r=$r_projects[$key]->finance_rule_money;
            $r_projects[$key]->finance_rule_money=number_format($r_projects[$key]->finance_rule_money,2);
            //融资总金额
            $r_projects[$key]->finance_money=number_format($finance_money,2);
            //项目已投人数
            $r_projects[$key]->user_num = $user_num;
            //项目已融资金额
            $r_projects[$key]->had_money =number_format($add_money,2) ;

        }
        return $r_projects;
    }

    /**返回详细预期收益
     * @param float $money
     * @return mixed
     */
    public function getProfit(float $money)
    {
        //查询分润各阶段投资人的总收益率
        $profit_rule = ProfitRole::where('profit_id', $this->profits_cate)//分润id
        ->where('role', 'User')//投资人
        ->sum('scale');
        $profit = $money * $profit_rule / 100;//年收益总金额
        //查询该项目的类型(月标还是天标，还本方式)
        switch($this->finance_time_cate){

            //“天”标
            case 'd':
                //每天收益
                $d_profit = $profit ;
                //取小数后两位
                $d_profit = floor($d_profit * 100);
                //$profit:该项目投资金额的实际收益
                $profit = $d_profit * $this->finance_time_num/ 360/ 100;
                //期数：30天一期
                $month = $this->finance_time_num %30==0?floor($this->finance_time_num / 30):floor($this->finance_time_num / 30)+1;
                //分期的收益(整期收益,剩余收益)
                $lists_profit=array($d_profit/ 360* 30/100,$d_profit/ 360 * ($this->finance_time_num % 30)/100);
                break;

            //“月”标
            case 'm':
                //每月收益
                $d_profit = $profit / 12;
                //取小数后两位
                $d_profit = floor($d_profit * 100) / 100;
                //$profit:该项目投资金额的实际收益
                $profit = $d_profit * $this->finance_time_num;
                //期数：每月一期
                $month=$this->finance_time_num;
                //分期收益(每月收益)
                $lists_profit=array($d_profit,$d_profit);
                break;

            //“自然月”标
            case 'mm':
                //每天收益
                $d_profit = $profit ;
                //取小数后两位
                $d_profit = floor($d_profit * 100) ;
                //$profit:该项目投资金额的实际收益
                $profit = $d_profit * $this->finance_time_num*30/ 360/ 100;
                //期数：30天一期
                $month = floor($this->finance_time_num / 30);
                //分期的收益(整期收益,剩余收益)
                $lists_profit=array($d_profit/ 360* 30/100,$d_profit/ 360 * ($this->finance_time_num % 30)/100);
                break;

//            case 'y':
//                $lists_profit;
//                break;
        }
        switch($this->repayment){

            //到期还本付息
            case 'sit':
                $month=0;
                break;

            //按月付息，到期还本
            case 'month':
                //还本金方式（分期的本金，最后一期的本金）
                $lists_capital=array('0',$money);
                break;

            //按月等额还本付息
            case 'profits_mode_three':
                //还本金方式（分期的本金，最后一期的本金）
                $lists_capital=array(round($money/$month,2,PHP_ROUND_HALF_DOWN),$money-($month-1)*round($money/$month,2,PHP_ROUND_HALF_DOWN));
                break;
            //先息后本
            case 'profits_mode_four':
                $month=2;
                $lists_profit=array($d_profit,'0');
                $lists_capital=array('0',$money);
                break;
        }
        $lists['all']['profit'] = $profit;
        $lists['all']['capital'] = $money;
        $lists['all']['all'] = $lists['all']['profit'] + $lists['all']['capital'];
        if($month!=0){
            $i=0;
            for ($i; $i <$month-1; $i++) {
                //每月收益记录
                $lists[$i]['key'] = $i + 1;
                $lists[$i]['profit'] = $lists_profit['0'];
                $lists[$i]['capital'] =$lists_capital['0'];
                $lists[$i]['all'] = $lists[$i]['profit']+$lists[$i]['capital'];
            }
            $lists[$i]['key'] = $i + 1;
            $lists[$i]['profit'] = $lists_profit['1'];
            $lists[$i]['capital'] =$lists_capital['1'];
            $lists[$i]['all'] = $lists[$i]['profit']+$lists[$i]['capital'];
        }
        else{
            $lists['0']['key'] = 1;
            $lists['0']['capital'] =$money;
            $lists['0']['profit'] =$profit;
            $lists['0']['all'] = $lists['0']['profit'] + $lists['0']['capital'];
        }
        $lists=$this->makeList($lists);
        return $lists;
    }

    /**
     * @param array $lists
     * @return array
     */
    private function makeList(array $lists)
    {
        foreach ($lists as $key => $list) {
            if (is_array($list)) {
                $list=$this->makeList($list);
            } else {
                if($key!='key'){
                    $list = number_format($list, 2);
                }
            }
            $lists[$key]=$list;
        }
        return $lists;
    }
}